<template>
  <div class="app-login">
    <h2>登录</h2>

    <div class="input-wrap">
      <MyInput type="text" placeholder="请输入账号" v-model="username" />
    </div>
    <div class="input-wrap">
      <MyInput type="password" placeholder="请输入密码" v-model="password" />
    </div>
    <div class="input-wrap">
      <MyButton
        text="登录"
        size="large"
        className="login-btn"
        @click="loginHandler"
      />
    </div>
  </div>
</template>

<script>
import MyButton from "../components/MyButton.vue";
import MyInput from "../components/MyInput.vue";
import { loginApi } from "../mocks/userApi";
import { mapMutations } from "vuex";

export default {
  name: "LoginView",
  data() {
    return {
      username: "",
      password: "",
    };
  },
  components: {
    MyInput,
    MyButton,
  },
  methods: {
    ...mapMutations(["userStore/loginMutaion"]),
    loginHandler() {
      let user = {
        username: this.username,
        password: this.password,
      };
      console.log(user);

      if (!user.username || !user.password) {
        return alert("请输入账号或者密码");
      }

      loginApi(user.username, user.password)
        .then((res) => {
          if (res.code == "200") {
            this["userStore/loginMutaion"]({
              username: user.username,
              userId: res.data.userId,
              token: res.data.token,
            });
            this.$router.push("/");
          } else {
            alert(res.msg);
          }
        })
        .catch((err) => {
          console.log("请求失败：", err);
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.app-login {
  width: 300px;
  margin: 100px auto;
  padding: 15px;
  box-shadow: 0 0 3px #ccc;

  .input-wrap {
    margin-top: 15px;
  }
}
</style>